<template>
 <div class="report-push-container">
  <div class="header-actions">
    <el-button @click="clickAdd" type="primary" :icon="Plus" class="add-button">新增推送信息</el-button>
  </div>
  
  <el-card class="table-card">
    <el-scrollbar>
      <div class="table-data">
        <el-table 
          :data="hookList" 
          v-loading="isLoading" 
          stripe 
          style="width: 100%" 
          empty-text="暂无数据" 
          border
          :header-cell-style="{background:'#f5f7fa', color: '#606266'}"
        >
          <el-table-column label="序号" align="center" width="60">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="推送名称" prop="name" align="center" />
          <el-table-column label="推送类型" prop="pushType" align="center">
            <template #default="scope">
              <el-tag 
                :type="getPushTypeTagType(scope.row.pushType)" 
                effect="plain"
              >
                <span class="push-type-tag">
                  <i :class="getPushTypeIconClass(scope.row.pushType)"></i>
                  {{ getPushTypeName(scope.row.pushType) }}
                </span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="hook地址" prop="webhook" align="center">
            <template #default="scope">
              <el-tooltip placement="top-start" effect="dark" :content="scope.row.webhook">
                <div class="webhook-text">{{ scope.row.webhook.length > 25 ? scope.row.webhook.slice(0, 25) + '...' : scope.row.webhook }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="接收人" prop="user_ids" align="center">
            <template #default="scope">
              <div class="user-tags">
                <el-tooltip 
                  v-if="scope.row.user_ids.length > 2" 
                  :content="scope.row.user_ids.join(', ')" 
                  placement="top"
                >
                  <div>
                    <el-tag v-for="(user, index) in scope.row.user_ids.slice(0, 2)" :key="index" size="small" class="user-tag">
                      {{ user }}
                    </el-tag>
                    <el-tag size="small" type="info">+{{ scope.row.user_ids.length - 2 }}</el-tag>
                  </div>
                </el-tooltip>
                <template v-else>
                  <el-tag v-for="(user, index) in scope.row.user_ids" :key="index" size="small" class="user-tag">
                    {{ user }}
                  </el-tag>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="测试计划" prop="testPlan.name" align="center"/>
          <el-table-column label="创建时间" align="center">
            <template #default="scope">
              {{ $tools.rTime(scope.row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button @click="clickEdit(scope.row)" size="small" type="primary" :icon="Edit" circle title="编辑"></el-button>
              <el-button @click="delHook(scope.row.id)" size="small" type="danger" :icon="Delete" circle title="删除"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container">
        <el-pagination 
          background 
          layout="total, prev, pager, next, jumper"
          @current-change="currentPages"
          :default-page-size="100"
          :total="pages.count"
          :current-page="pages.current"
          :next-text="'下一页'" 
          :prev-text="'上一页'"
        >
        </el-pagination>
      </div>
    </el-scrollbar>
  </el-card>

  <!--  新增弹窗-->
  <el-dialog 
    v-model="addDlg" 
    title="新增推送信息" 
    width="40%" 
    custom-class="push-dialog" 
    :required="true" 
    style="text-align:left" 
    :before-close="clearValidation"
    top="5vh"
  >
    <el-form :model="addForm" :rules="rulesHook" ref="HookRef" label-width="120px" style="max-width: 600px">
      <el-form-item prop="name" label="推送名称">
        <el-input v-model="addForm.name" maxlength="50" minlength="1" placeholder="请输入推送名称"/>
      </el-form-item>
      
      <el-form-item prop="pushType" label="推送类型">
        <el-radio-group v-model="addForm.pushType" class="push-type-group">
          <el-radio-button label="wechat">
            <span class="push-icon-wrapper">
              <i class="iconfont icon-wechat"></i> 企业微信
            </span>
          </el-radio-button>
          <el-radio-button label="feishu">
            <span class="push-icon-wrapper">
              <i class="iconfont icon-feishu"></i> 飞书
            </span>
          </el-radio-button>
          <el-radio-button label="dingtalk">
            <span class="push-icon-wrapper">
              <i class="iconfont icon-dingtalk"></i> 钉钉
            </span>
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item prop="webhook" label="webhook地址">
        <el-input v-model="addForm.webhook" minlength="3" placeholder="请输入webhook地址" show-word-limit>
          <template #prefix>
            <i :class="[getPushTypeIconClass(addForm.pushType), 'iconfont']"></i>
          </template>
        </el-input>
        <div class="webhook-tip" v-if="addForm.pushType">
          <el-link type="primary" :href="getWebhookHelpUrl(addForm.pushType)" target="_blank">
            <i class="el-icon-question"></i> 如何获取{{ getPushTypeName(addForm.pushType) }}的webhook地址?
          </el-link>
        </div>
      </el-form-item>
      
      <el-form-item prop="testPlan_id" label="测试计划">
        <el-select v-model="addForm.testPlan_id" placeholder="请选择测试计划" style="width: 100%;">
          <el-option :label="iter.name" :value="iter.id" v-for="iter in testPlans" :key="iter.id"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="接收人" prop="user_ids">
        <el-select multiple v-model="addForm.user_ids" placeholder="请选择接收人" style="width: 100%;" collapse-tags collapse-tags-tooltip @change="handleReceiversChange('add')">
          <el-option :label="'@all'" :value="'@all'" :key="'@all'" :disabled="addForm.user_ids.length > 0 && !addForm.user_ids.includes('@all')"></el-option>
          <el-option 
            :label="iter.weChat_name" 
            :value="iter.weChat_name" 
            v-for="iter in filteredUsers" 
            :key="iter.id" 
            :disabled="addForm.user_ids.includes('@all')"
          ></el-option>
        </el-select>
        <div class="form-tip">选择 @all 将通知所有人，与其他接收人互斥</div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clearValidation" size="default">取消</el-button>
        <el-button type="primary" @click="AddInter" size="default">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!--  修改弹窗-->
  <el-dialog 
    v-model="editDlg" 
    title="修改推送信息" 
    width="40%"
    custom-class="push-dialog" 
    :required="true" 
    style="text-align:left" 
    :before-close="clearValidation"
    top="5vh"
  >
    <el-form :model="editForm" :rules="rulesHook" ref="HookRef" label-width="120px" style="max-width: 600px">
      <el-form-item prop="name" label="推送名称">
        <el-input v-model="editForm.name" maxlength="50" minlength="1" placeholder="请输入推送名称"/>
      </el-form-item>
      
      <el-form-item prop="pushType" label="推送类型">
        <el-radio-group v-model="editForm.pushType" class="push-type-group">
          <el-radio-button label="wechat">
            <span class="push-icon-wrapper">
              <i class="iconfont icon-wechat"></i> 企业微信
            </span>
          </el-radio-button>
          <el-radio-button label="feishu">
            <span class="push-icon-wrapper">
              <i class="iconfont icon-feishu"></i> 飞书
            </span>
          </el-radio-button>
          <el-radio-button label="dingtalk">
            <span class="push-icon-wrapper">
              <i class="iconfont icon-dingtalk"></i> 钉钉
            </span>
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item prop="webhook" label="webhook地址">
        <el-input v-model="editForm.webhook" minlength="3" placeholder="请输入webhook地址" show-word-limit>
          <template #prefix>
            <i :class="[getPushTypeIconClass(editForm.pushType), 'iconfont']"></i>
          </template>
        </el-input>
        <div class="webhook-tip" v-if="editForm.pushType">
          <el-link type="primary" :href="getWebhookHelpUrl(editForm.pushType)" target="_blank">
            <i class="el-icon-question"></i> 如何获取{{ getPushTypeName(editForm.pushType) }}的webhook地址?
          </el-link>
        </div>
      </el-form-item>
      
      <el-form-item prop="testPlan_id" label="测试计划">
        <el-select v-model="editForm.testPlan_id" placeholder="请选择测试计划" style="width: 100%;">
          <el-option :label="iter.name" :value="iter.id" v-for="iter in testPlans" :key="iter.id"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="接收人" prop="user_ids">
        <el-select multiple v-model="editForm.user_ids" placeholder="请选择接收人" style="width: 100%;" collapse-tags collapse-tags-tooltip @change="handleReceiversChange('edit')">
          <el-option :label="'@all'" :value="'@all'" :key="'@all'" :disabled="editForm.user_ids.length > 0 && !editForm.user_ids.includes('@all')"></el-option>
          <el-option 
            :label="iter.weChat_name" 
            :value="iter.weChat_name" 
            v-for="iter in filteredUsers" 
            :key="iter.id" 
            :disabled="editForm.user_ids.includes('@all')"
          ></el-option>
        </el-select>
        <div class="form-tip">选择 @all 将通知所有人，与其他接收人互斥</div>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clearValidation" size="default">取消</el-button>
        <el-button type="primary" @click="EditInter" size="default">确定</el-button>
      </span>
    </template>
  </el-dialog>
</div>
</template>


<script>
import {mapActions, mapState} from "vuex";
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  data() {
    return {
      hookList:'',
      pages:'',
      addDlg:false,
      isLoading: false,
      editDlg: false,
      Plus,
      Edit,
      Delete,
      pushTypeOptions: [
        { value: 'wechat', label: '企业微信' },
        { value: 'feishu', label: '飞书' },
        { value: 'dingtalk', label: '钉钉' }
      ],
      addForm:{
        name: '',
        webhook: '',
        user_ids: [],
        project_id: '',
        testPlan_id: '',
        pushType: 'wechat', // 默认为企业微信
      },
      editForm:{
        name: '',
        webhook: '',
        user_ids: [],
        project_id: '',
        testPlan_id: '',
        pushType: 'wechat',
      },
      rulesHook: {
        // 验证用户名是否合法
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }
        ],
        // 验证推送类型
        pushType: [
          {
            required: true,
            message: '请选择推送类型',
            trigger: 'change'
          }
        ],
        // 验证webhook地址
        webhook: [
          {
            required: true,
            message: '请输入webhook地址',
            trigger: 'blur'
          }
        ],
        testPlan_id: [
          {
            required: true,
            message: '请选择测试计划',
            trigger: 'blur'
          }
        ],
        user_ids: [
          {
            type: 'array',
            required: true,
            message: '请选择至少一个接收人',
            trigger: 'change'
          }
        ]
      }
    }},
  computed: {
    ...mapState(['pro','testPlans','Users']),
    filteredUsers() {
      const filtered = this.Users.filter(iter => iter.weChat_name !== null);
      return filtered
    }
  },

  methods: {
    ...mapActions(['getAllUser']),
    
    // 处理接收人选择逻辑
    handleReceiversChange(formType) {
      const form = formType === 'add' ? this.addForm : this.editForm;
      
      // 如果选择了@all，清除其他所有选择
      if (form.user_ids.includes('@all')) {
        form.user_ids = ['@all'];
      }
      
      // 确保数组不为空，如果为空则验证会失败
      if (form.user_ids.length === 0) {
        this.$refs.HookRef.validateField('user_ids');
      }
    },
    
    // 获取推送类型名称
    getPushTypeName(type) {
      const map = {
        'wechat': '企业微信',
        'feishu': '飞书',
        'dingtalk': '钉钉'
      };
      return map[type] || '未知';
    },
    
    // 获取推送类型对应的Tag类型
    getPushTypeTagType(type) {
      const map = {
        'wechat': 'success',
        'feishu': 'info',
        'dingtalk': 'warning'
      };
      return map[type] || 'info';
    },
    
    // 获取推送类型的图标样式
    getPushTypeIconClass(type) {
      const map = {
        'wechat': 'icon-wechat',
        'feishu': 'icon-feishu',
        'dingtalk': 'icon-dingtalk'
      };
      return map[type] || '';
    },
    
    // 获取不同推送类型的帮助链接
    getWebhookHelpUrl(type) {
      const map = {
        'wechat': 'https://developer.work.weixin.qq.com/document/path/91770',
        'feishu': 'https://open.feishu.cn/document/ukTMukTMukTM/ucTM5YjL3ETO24yNxkjN',
        'dingtalk': 'https://open.dingtalk.com/document/robots/custom-robot-access'
      };
      return map[type] || '#';
    },

    // 点击添加
    clickAdd() {
      this.addDlg = true;
      this.addForm = {
        name: '',
        webhook: '',
        user_ids: [],
        project_id: this.pro.id,
        testPlan_id: '',
        pushType: 'wechat', // 默认企业微信
      }
    },
    
    // 点击修改
    clickEdit(info) {
      this.editDlg = true;
      this.editForm = { ...info };
      // 如果没有pushType字段(兼容老数据)，默认为企业微信
      if (!this.editForm.pushType) {
        this.editForm.pushType = 'wechat';
      }
      this.editForm.project_id = this.pro.id;
    },

    // 点击删除
    delHook(id) {
      ElMessageBox.confirm('此操作将永久删除该推送信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const response = await this.$api.delHook(id)
          if(response.status ===204){
            ElMessage({
              type: 'success',
              message: '删除成功!'
            });
            // 刷新页面
            this.getAllHook(this.pro)
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    // 点击关闭弹窗
    clearValidation() {
      this.addDlg = false;
      this.editDlg = false;
      this.$refs.HookRef.clearValidate(); // 清除验证信息
    },
    
    // 列表数据展示
    async getAllHook(){
      this.isLoading=true;
      const response = await this.$api.getHook(this.pro.id)
      if (response.status === 200){
        this.hookList = response.data.result;
        this.pages = response.data
        // 遍历每条记录并处理user_ids字段
        this.hookList.forEach(record => {
          const userIDs = eval(record.user_ids);
          record.user_ids = userIDs;
          // 如果没有pushType字段(兼容老数据)，默认为企业微信
          if (!record.pushType) {
            record.pushType = 'wechat';
          }
        });
      }
      this.isLoading=false;
    },
    
    // 新增接口
    async AddInter(){
      this.$refs.HookRef.validate(async valid => {
        // 判断是否验证通过，不通过则直接return
        if (!valid) return;
        // 调用接口等逻辑
        const params = {...this.addForm}
        const formattedIds = params.user_ids.map(id => `'${id}'`); // 在每个元素周围添加单引号
        params.user_ids = `[${formattedIds.join(',')}]`; // 将数组转换为字符串，并使用方括号括起来

        const response = await this.$api.createHook(params)
        if (response.status===201) {
          ElMessage({
            type: 'success',
            message: '添加成功',
            duration: 1000})

          this.addForm = {
            name: '',
            webhook: '',
            user_ids: [],
            project_id: '',
            testPlan_id: '',
            pushType: 'wechat',
          };
          this.addDlg = false;
          this.getAllHook()
        }
      })
    },
    
    // 修改接口
    async EditInter(){
      this.$refs.HookRef.validate(async valid => {
        if (!valid) return
        const params = {...this.editForm}
        const formattedIds = params.user_ids.map(id => `'${id}'`); // 在每个元素周围添加单引号
        params.user_ids = `[${formattedIds.join(',')}]`; // 将数组转换为字符串，并使用方括号括起来
        const response = await this.$api.updateHook(params.id, params)
        if (response.status===200) {
          ElMessage({
            type: 'success',
            message: '修改成功',
            duration: 1000});

          this.editForm = {
            name: '',
            webhook: '',
            user_ids: [],
            project_id: '',
            testPlan_id: '',
            pushType: 'wechat',
          };
          this.editDlg = false;
          this.getAllHook()
        }
      })
    },
    
    currentPages(currentPage) {
      this.getAllHook(currentPage)
      this.hookList.page = currentPage;
    },
  },

  created() {
    this.getAllHook()
    this.getAllUser()
  }
}
</script>

<style scoped>
.report-push-container {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
}

.add-button {
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.table-data {
  margin-bottom: 20px;
}

.webhook-text {
  font-family: monospace;
  color: #606266;
}

.user-tags {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 4px;
}

.user-tag {
  margin: 2px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.push-dialog .el-dialog__body {
  padding-top: 10px;
}

.push-type-group {
  display: flex;
  width: 100%;
}

.push-type-group .el-radio-button {
  flex: 1;
  text-align: center;
}

.push-type-group .el-radio-button__inner {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.webhook-tip {
  margin-top: 5px;
  font-size: 12px;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.push-type-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.push-icon-wrapper {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 使用iconfont图标 */
@font-face {
  font-family: "iconfont";
  src: url('//at.alicdn.com/t/font_2093840_x29ov0mu3d.eot');
  src: url('//at.alicdn.com/t/font_2093840_x29ov0mu3d.eot?#iefix') format('embedded-opentype'),
       url('//at.alicdn.com/t/font_2093840_x29ov0mu3d.woff2') format('woff2'),
       url('//at.alicdn.com/t/font_2093840_x29ov0mu3d.woff') format('woff'),
       url('//at.alicdn.com/t/font_2093840_x29ov0mu3d.ttf') format('truetype');
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-wechat:before {
  content: "\e6e1";
  color: #07c160;
}

.icon-feishu:before {
  content: "\e639";
  color: #3370ff;
}

.icon-dingtalk:before {
  content: "\e890";
  color: #1890ff;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .push-dialog {
    width: 90% !important;
  }
  
  .push-type-group {
    flex-direction: column;
  }
}
</style>